import {defineStore} from 'pinia'
import categoryApi from '@/api/category'
import type{ CategoryData } from '@/api/category'
import { ElMessage } from 'element-plus'
import type{ AxiosError } from 'axios'

interface CategoryStoreStateData{
  category1List:CategoryData[],
  category1Id:string | number
  category2List:CategoryData[],
  category2Id:string | number
  category3List:CategoryData[],
  category3Id:string | number
}
export const useCategoryStore=defineStore('category',{
  state():CategoryStoreStateData{
    return{
      category1List:[],
      category1Id:'',
      category2List:[],
      category2Id:'',
      category3List:[],
      category3Id:'',
    }
  },
  actions:{
    async getCategory1List(){
      try {
        const res=await categoryApi.getCategory1()
        this.category1List=res
      } catch (error) {
        ElMessage.error('取一级分类列表失败' + (error as AxiosError).message)
      }
    },
        // 获取二级分类的请求逻辑
        async getCategory2List(){
          this.category2List=[]
          this.category2Id=''
          this.category3List=[]
          this.category3Id=''
          try {
            // 发送api请求
            const res = await categoryApi.getCategory2(this.category1Id as number)
            // 把获取到的一级分类数据存到state当中
            this.category2List = res
          } catch (error) {
            ElMessage.error('取二级分类列表失败' + (error as AxiosError).message)
          }
        },
         // 获取三级分类的请求逻辑
    async getCategory3List(){
      this.category3List=[]
      this.category3Id=''
      try {
        // 发送api请求
        const res = await categoryApi.getCategory3(this.category2Id as number)
        // 把获取到的一级分类数据存到state当中
        this.category3List = res
      } catch (error) {
        ElMessage.error('取三级分类列表失败' + (error as AxiosError).message)
      }
    }
  },


  getters:{

  }
})